import 'dart:async';

import 'package:flutter/material.dart';
import 'package:zhibao_flutter/util/check/check.dart';
import 'package:zhibao_flutter/util/event_bus/number_event.dart';
import 'package:zhibao_flutter/widget/view/my_gradent_text.dart';

class DynamicNumber extends StatefulWidget {
  final double fullHeight;
  final double fontSize;
  final int index;
  final String valueUse;

  const DynamicNumber(this.fullHeight, this.fontSize, this.index, this.valueUse,
      {Key? key})
      : super(key: key);

  @override
  State<DynamicNumber> createState() => _DynamicNumberState();
}

class _DynamicNumberState extends State<DynamicNumber>
    with TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  String valueUseUp = "";
  String valueUse = "";

  late AnimationController controller;
  late Animation<double> animation;

  StreamSubscription? eventBusOfNumBerValue;

  double get fullHeight => widget.fullHeight;

  @override
  void initState() {
    super.initState();

    eventBusOfNumBerValue =
        eventBusOfNumBer.on<EventBusOfNumBerModel>().listen((event) async {
      if (widget.index != event.index) {
        return;
      }
      if (event.type == 1 || event.value == null) {
        deleteValue(event).then((value) {
          eventBusOfNumBer.fire(RefreshHomePriceModel());
        });
        return;
      }
      insertValue(event);
    });
    controller = AnimationController(
      vsync: this,
      duration: Duration(milliseconds: 300),
    );
    controller.addStatusListener((status) {
      print("controller::${status.toString()}");
    });
    animation = CurvedAnimation(parent: controller, curve: Curves.easeInOut);

    insertValue(EventBusOfNumBerModel(widget.valueUse, 0, 0));
  }

  Future deleteValue(event) async {
    valueUseUp = "";
    print("valueUseUp：：$valueUseUp");
    print("valueUse：：$valueUse");
    if (mounted) setState(() {});
    controller.reset();
    await controller.forward();
    valueUseUp = valueUse;
  }

  Future insertValue(event) async {
    if (strNoEmpty(valueUse) &&
        strNoEmpty(event.value) &&
        int.parse(valueUse) > int.parse(event.value!)) {
      valueUseUp = event.value.toString();
      print("valueUseUp：：$valueUseUp");
      print("valueUse：：$valueUse");
      if (mounted) setState(() {});
      controller.reset();
      await controller.forward();
      valueUseUp = valueUse;
      valueUse = event.value!;
      print("[after] valueUseUp：：$valueUseUp");
      print("[after] valueUse：：$valueUse");
      if (mounted) setState(() {});
      controller.reset();
    } else {
      valueUseUp = valueUse;
      valueUse = event.value.toString();
      print("valueUseUp：：$valueUseUp");
      print("valueUse：：$valueUse");
      if (mounted) setState(() {});
      await controller.animateTo(1, duration: Duration(milliseconds: 0));
      controller.reverse();
    }
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return Container(
      child: Stack(
        children: [
          Container(
            height: fullHeight,
            alignment: Alignment.center,
            child: Column(
              children: [
                NumberBuild(
                    fullHeight, animation, valueUseUp, false, widget.fontSize),
                NumberBuild(
                    fullHeight, animation, valueUse, false, widget.fontSize),
                SizedBox(height: fullHeight / 3)
              ],
            ),
          ),
          Positioned(
            top: 0,
            right: 0,
            left: 0,
            height: fullHeight / 3,
            child: Container(
              color: Colors.white,
            ),
          ),
          Positioned(
            bottom: 0,
            right: 0,
            left: 0,
            height: fullHeight / 3,
            child: Container(
              color: Colors.white,
            ),
          ),
        ],
      ),
    );
  }

  @override
  void deactivate() {
    super.deactivate();
    eventBusOfNumBerValue?.cancel();
    eventBusOfNumBerValue = null;
    controller.dispose();
  }

  @override
  bool get wantKeepAlive => true;
}

class NumberBuild extends StatelessWidget {
  final double fullHeight;
  final Animation<double> animation;
  final String valueUse;
  final bool down;
  final double fontSize;

  NumberBuild(
      this.fullHeight, this.animation, this.valueUse, this.down, this.fontSize);

  @override
  Widget build(BuildContext context) {
    return Container(
      height: fullHeight / 3,
      alignment: Alignment.center,
      child: AnimatedBuilder(
        animation: animation,
        builder: (BuildContext context, Widget? child) {
          Animation<Offset> useOffset = Tween<Offset>(
            begin: Offset(0, 0 + (down ? 1 : 0)),
            end: Offset(0, 1 + (down ? 1 : 0)),
          ).animate(animation);
          return SlideTransition(
            position: useOffset,
            child: Container(
              height: fullHeight / 3,
              alignment: Alignment.center,
              child: MyGradentText(
                valueUse.toString(),
                style: TextStyle(
                  fontSize: fontSize,
                  fontWeight: FontWeight.w600,
                ),
              ),
            ),
          );
        },
      ),
    );
  }
}
